package com.jeeplus.test.jlnu.archivalBatch.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.test.jlnu.archivalBatch.domain.JlnuArchivalBatch;
import com.jeeplus.test.jlnu.archivalBatch.domain.JlnuArchivalInfoBatch;
import com.jeeplus.test.jlnu.archivalBatch.mapper.JlnuArchivalBatchMapper;
import com.jeeplus.test.jlnu.archivalBatch.service.JlnuArchivalBatchService;
import com.jeeplus.test.jlnu.archivalBatch.util.DateUtils;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoReqVo;
import com.jeeplus.test.jlnu.archivalInfo.service.ArchivalInfoService;
import liquibase.pro.packaged.S;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class JlnuArchivalBatchServiceImpl implements JlnuArchivalBatchService {


    @Autowired
    private OfficeService officeService;
    @Autowired
    private JlnuArchivalBatchMapper jlnuArchivalBatchMapper;

    @Autowired
    private ArchivalInfoService archivalInfoService;

    public int insert(JlnuArchivalBatch jlnuArchivalBatch) {
        return jlnuArchivalBatchMapper.insert(jlnuArchivalBatch);
    }

    public int deleteById(Integer id) {
        return jlnuArchivalBatchMapper.deleteById(id);
    }

    public int update(JlnuArchivalBatch jlnuArchivalBatch) {
        return jlnuArchivalBatchMapper.update(jlnuArchivalBatch);
    }

    public JlnuArchivalBatch selectById(Integer id) {
        return jlnuArchivalBatchMapper.selectById(id);
    }

    public List<JlnuArchivalBatch> selectAll() {
        return jlnuArchivalBatchMapper.selectAll();
    }

    @Override
    public void approval(List<JlnuArchivalBatch> jlnuArchivalBatch) {
        Integer batchId = null;
        String approveState = "";
        List<ArchivalInfoReqVo> archivalInfoReqVos = new ArrayList<>();
        for (JlnuArchivalBatch archivalBatch : jlnuArchivalBatch) {
            //批量提交，生成批次名称，当前部门+日期+序号
            approveState = archivalBatch.getApproveState();
            if ("2".equals(archivalBatch.getApproveState())) {
                //查询当前序号
                if (null == batchId) {
                    batchId = getBatchId(archivalBatch);
                }

                JlnuArchivalInfoBatch archivalInfoBatch = new JlnuArchivalInfoBatch();
                //插入关联表
                archivalInfoBatch.setBatchId(batchId);
                archivalInfoBatch.setInfoId(archivalBatch.getInfoId());
                jlnuArchivalBatchMapper.insertInfoBatch(archivalInfoBatch);

                //修改info表状态
                ArchivalInfoReqVo archivalInfoReqVo = new ArchivalInfoReqVo();
                archivalInfoReqVo.setId(archivalBatch.getInfoId());
                archivalInfoReqVo.setApproveState(archivalBatch.getApproveState());
                archivalInfoService.updateArchival(archivalInfoReqVo);

            }
            if ("3".equals(archivalBatch.getApproveState()) ||
                    "4".equals(archivalBatch.getApproveState())) {
                //查询当前序号
                if (null == batchId) {
                    batchId = archivalBatch.getBatchId();
                    //删除根据batchId删除关联表数据
                    JlnuArchivalInfoBatch archivalInfoBatch = new JlnuArchivalInfoBatch();
                    archivalInfoBatch.setBatchId(batchId);
                    jlnuArchivalBatchMapper.deleteInfoBatchByBatchId(archivalInfoBatch);
                    //更新batch表状态
                    JlnuArchivalBatch archivalBatch1 = new JlnuArchivalBatch();
                    archivalBatch1.setId(batchId);
                    archivalBatch1.setApproveState(archivalBatch.getApproveState());
                    jlnuArchivalBatchMapper.update(archivalBatch1);

                }

                JlnuArchivalInfoBatch archivalInfoBatch = new JlnuArchivalInfoBatch();
                //插入关联表
                archivalInfoBatch.setBatchId(batchId);
                archivalInfoBatch.setInfoId(archivalBatch.getInfoId());
                archivalInfoBatch.setApproveRemark(archivalBatch.getApproveRemark());
                archivalInfoBatch.setApproveState(archivalBatch.getApproveState());
                jlnuArchivalBatchMapper.insertInfoBatch(archivalInfoBatch);

                //修改info表状态
                ArchivalInfoReqVo archivalInfoReqVo = new ArchivalInfoReqVo();
                archivalInfoReqVo.setId(archivalBatch.getInfoId());
                archivalInfoReqVo.setApproveState(archivalBatch.getApproveState());
                archivalInfoReqVo.setApproveRemark(archivalBatch.getApproveRemark());
                if ("3".equals(archivalBatch.getApproveState())) {
                    //审批通过生成材料号
                    archivalInfoReqVo.setMaterialId("");
                }
                archivalInfoService.updateArchival(archivalInfoReqVo);
                ArchivalInfoReqVo archivalInfoById =
                        archivalInfoService.getArchivalInfoById(archivalBatch.getInfoId());
                archivalInfoReqVos.add(archivalInfoById);

            }

        }
        //审批通过处理材料号
        if ("3".equals(approveState)) {
            List<ArchivalInfoReqVo> copiedList = archivalInfoReqVos.stream()
                    .collect(Collectors.toList());  // 使用流复制
            for (ArchivalInfoReqVo archivalBatch : archivalInfoReqVos) {

                //根据学号查询是否存在材料号
                Map param = new HashMap();
                param.put("studentId", archivalBatch.getStudentId());
                param.put("materialSort", archivalBatch.getMaterialSort());
                param.put("flag", "1");
                List<Map<String, String>> data = archivalInfoService.querylist(param);
                String materialIdInfo = archivalBatch.getMaterialSort() + ".";
                if (!CollectionUtils.isEmpty(data)) {
                    String materialId = data.get(0).get("material_id");
                    String[] split = materialId.split("\\.");
                    String increment = increment(split[1]);
                    materialIdInfo += increment;

                } else {
                    materialIdInfo += "0001";
                }
                List<ArchivalInfoReqVo> filteredList = copiedList.stream()
                        .filter(item -> archivalBatch.getStudentId().equals(item.getStudentId())
                                && item.getMaterialSort().equals(archivalBatch.getMaterialSort()))  // 先过滤出 StudentId 等于 22 的数据
                        .sorted((item1, item2) -> item1.getDateTime().compareTo(item2.getDateTime()))  // 按照 dateTime 倒序排序
                        .collect(Collectors.toList());  // 收集结果到 List 中

                // 获取过滤和排序后的第一个对象
                if (!filteredList.isEmpty()) {
                    ArchivalInfoReqVo archivalInfoReqVo = filteredList.get(0);  // 获取第一个对象
                    // 移除该对象
                    copiedList.remove(archivalInfoReqVo);  // 从 filteredList 中移除该对象
                    archivalInfoReqVo.setMaterialId(materialIdInfo);
                    archivalInfoService.updateArchival(archivalInfoReqVo);
                }


            }
        }


    }

    @Override
    public Page<JlnuArchivalBatch> getArchivalBatchPage(JlnuArchivalBatch archivalInfoReqVo, Page<JlnuArchivalBatch> page) {
        // 1. 获取分页结果和字段配置信息
        if (StringUtils.isNotEmpty(archivalInfoReqVo.getOfficeId())) {
            Office byId = officeService.getById(archivalInfoReqVo.getOfficeId());
            if ("6".equals(byId.getType())) {
                //如果是档案馆
                //获取机构下所有层级
                List<String> officesList = officeService.getOfficesTreeByParentId(archivalInfoReqVo.getOfficeId());
                officesList.add(archivalInfoReqVo.getOfficeId());
                archivalInfoReqVo.setOfficesList(officesList);
                archivalInfoReqVo.setOfficeId("");
            }
        }

        // 处理type
        if (StringUtils.isNotEmpty(archivalInfoReqVo.getApproveState())) {
            String[] arr = archivalInfoReqVo.getApproveState().split(",");
            List<String> list = Arrays.asList(arr);
            archivalInfoReqVo.setApproveStateList(list);
        }


        Page<JlnuArchivalBatch> archivalInfoPage = jlnuArchivalBatchMapper.getArchivalInfoPage(archivalInfoReqVo, page);

        return archivalInfoPage;
    }

    private Integer getBatchId(JlnuArchivalBatch archivalBatch) {

        JlnuArchivalBatch archivalBatch1 = new JlnuArchivalBatch();
        Office byId = officeService.getById(archivalBatch.getOfficeId());

        String name = byId.getName();
        String currentDate = DateUtils.getCurrentDate();
        name += currentDate;
        archivalBatch.setName(name);
        String count = jlnuArchivalBatchMapper.selectName(archivalBatch);
        if (null == count) {
            name += "0001";
        } else {
            name += increment(count);
        }
        archivalBatch1.setName(name);
        archivalBatch1.setApproveState(archivalBatch.getApproveState());
        archivalBatch1.setOfficeId(archivalBatch.getOfficeId());
        //archivalBatch1.setName();
        jlnuArchivalBatchMapper.insert(archivalBatch1);
        return archivalBatch1.getId();
    }

    public static String increment(String input) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入字符串不能为空");
        }

        // 检查输入是否全是数字
        if (!input.matches("\\d+")) {
            throw new IllegalArgumentException("输入字符串必须为数字格式");
        }

        // 获取字符串的长度
        int length = input.length();

        // 将字符串转换为整数并加一
        int number = Integer.parseInt(input);
        number += 1;

        // 将结果转换回字符串，并补齐前导零
        String result = String.format("%0" + length + "d", number);

        return result;
    }
}
